﻿using Credera.Theta.API;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Credera.Theta.Modules.Environments.Commands
{
    [Command("RemoveEnvironmentModule")]
    [Synopsis("Removes the specified environment module")]
    class RemoveEnvironmentModuleCommand : InputCommand
    {
        [Parameter(ordinalPosition: 1, autoCompleteValuesFunction: "GetEnvironmentNamesAutoComplete", useAutoCompleteForValidation: true)]
        [Synopsis("The name of the environment to remove the module from")]
        public string Environment { get; set; }

        [Parameter(ordinalPosition: 2, autoCompleteValuesFunction: "GetModuleNameAutoComplete", useAutoCompleteForValidation:true)]
        [Synopsis("The name of the module to remove")]
        public string Module { get; set; }

        public override void Invoke(CommandInvocationContext context)
        {
            if (base.Confirm("The module will be removed."))
            {
                var env = EnvironmentLogic.Instance.EnvironmentsCollection.Environments
                    .FirstOrDefault(e => e.Name.Equals(this.Environment, StringComparison.OrdinalIgnoreCase));

                env.Modules.Remove(env.Modules.FirstOrDefault(m => m.Name.Equals(this.Module, StringComparison.OrdinalIgnoreCase)));

                EnvironmentLogic.Instance.Save();

                base.Out.Object.Table(TableRecords.CreateEnvironmentRecordList(env));

                if (EnvironmentLogic.Instance.LoadedEnvironments.Contains(env))
                    base.Out.Warning.WriteLine("This environment is currently loaded and must be reloaded before the changes will take effect");
            }
        }

        public void GetEnvironmentNamesAutoComplete(AutoCompleteValuesFunctionContext context)
        {
            context.Values.AddRange(EnvironmentLogic.Instance.EnvironmentsCollection.Environments.Select(e => e.Name));
        }

        public void GetModuleNameAutoComplete(AutoCompleteValuesFunctionContext context)
        {
            if (string.IsNullOrWhiteSpace(this.Environment))
                return;

            context.Values.AddRange(
                EnvironmentLogic.Instance.EnvironmentsCollection.Environments
                .FirstOrDefault(e => e.Name.Equals(this.Environment, StringComparison.OrdinalIgnoreCase))
                .Modules.Select(m => m.Name));
        }
    }
}
